package com.linkpow.smartelevator.config;

import com.fasterxml.jackson.databind.JavaType;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
/**
 * @ClassName MyMappingJackson2HttpMessageConverter
 * @Description 输出Jackson转换日志
 * @Author Administrator
 * @Date 2019/11/25 13:39
 * @Version 1.0
 */
public class MyMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        logger.info("-开始读取请求内容-");
        return readJavaType(type, contextClass, inputMessage);
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        logger.info("-开始读取请求内容-");
        return readJavaType(null, clazz, inputMessage);
    }

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        logger.info("-开始写入回复内容-");
        String respStr = super.getObjectMapper().writeValueAsString(object);
        logger.info("平台服务端发送回复报文内容：" + respStr);
        outputMessage.getBody().write(respStr.getBytes("UTF-8"));
    }

    private Object readJavaType(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException{
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            InputStream sis = inputMessage.getBody();
            while ((count = sis.read(buffer, 0, buffer.length)) > 0) {
                baos.write(buffer, 0, count);
            }
            byte[] readBytes = baos.toByteArray();
            String reqStr = new String(readBytes, "UTF-8");
            logger.info("平台服务端获取请求报文内容：" + reqStr);
            JavaType javaType = getJavaType(type, contextClass);
            return super.getObjectMapper().readValue(reqStr, javaType.getRawClass());
        } catch (UnsupportedEncodingException e) {
            logger.error("平台服务端接收请求获取请求报文时失败", e);
            throw new IOException("平台服务端接收请求获取请求报文时失败", e);
        } catch (IOException e) {
            logger.error("平台服务端接收请求获取请求报文时失败", e);
            throw new IOException("平台服务端接收请求获取请求报文时失败", e);
        }
    }
}
